package com.example.heimashop.view.adapter;

import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.heimashop.databinding.ItemOrderGoodsBinding;
import com.example.heimashop.model.CartItem;
import com.example.heimashop.utils.GlideUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * 订单商品列表适配器
 */
public class OrderGoodsAdapter extends RecyclerView.Adapter<OrderGoodsAdapter.ViewHolder> {

    private List<CartItem> goodsList = new ArrayList<>();

    public void setData(List<CartItem> list) {
        if (list != null) {
            this.goodsList = list;
            notifyDataSetChanged();
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemOrderGoodsBinding binding = ItemOrderGoodsBinding.inflate(
                LayoutInflater.from(parent.getContext()),
                parent,
                false
        );
        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        CartItem item = goodsList.get(position);
        holder.bind(item);
    }

    @Override
    public int getItemCount() {
        return goodsList.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        private final ItemOrderGoodsBinding binding;

        ViewHolder(ItemOrderGoodsBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        void bind(CartItem item) {
            binding.tvName.setText(item.getGoodsName());
            binding.tvPrice.setText(String.format(Locale.CHINA, "¥%.2f", item.getGoodsPrice()));
            binding.tvCount.setText(String.format("x%d", item.getGoodsCount()));

            // 加载图片
            if (item.getGoodsImage() != null && !item.getGoodsImage().isEmpty()) {
                GlideUtils.loadImage(binding.getRoot().getContext(), item.getGoodsImage(), binding.ivGoods);
            }
        }
    }
}
